<template>
    <div>
        <el-form ref="ruleFormRef" :model="form" :rules="rules" class="form-box" label-width="120px">
            <el-form-item prop="username" label="用户姓名">
                <el-input v-model="form.username" placeholder="用户姓名" />
            </el-form-item>
            <el-form-item prop="mobile" label="用户电话">
                <el-input v-model="form.mobile" placeholder="用户电话" maxlength="11" />
            </el-form-item>
            <el-form-item prop="password" label="登录密码">
                <el-input v-model="form.password" type="password" placeholder="不填，表示不修改原来的密码" />
            </el-form-item>
            <el-form-item prop="level" label="用户等级">
                <el-select v-model="form.level" placeholder="请选择用户等级" style="width: 100%" clearable>
                    <el-option v-for="item in levelList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="cancle(ruleFormRef)">取 消</el-button>
                <el-button type="primary" @click="ok(ruleFormRef)">确 认</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import {reactive, ref, onMounted} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import api from './api/index'
import {successDeal, setStore, removeStore} from '@/utils/utils'
const $router = useRouter()
const $route = useRoute()
const form = reactive({
    username: '',
    mobile: '',
    password: '',
    level: 1,
    id: '',
})

const levelList = [
    {
        value: 1,
        label: '一级',
    },
    {
        value: 2,
        label: '二级',
    },
]

const rules = reactive({
    username: [{required: true, message: '请输入用户姓名', trigger: 'blur'}],
    mobile: [
        {required: true, message: '请输入手机号码', trigger: 'blur'},
        {
            pattern: /^1[3|4|5|6|7|8|9]\d{9}$/,
            message: '手机号格式错误',
            trigger: 'change',
        },
    ],
    level: [{required: true, message: '请选择用户等级', trigger: 'change'}],
})

onMounted(() => {
    form.id = $route.query.id
    getInfo()
})

const getInfo = () => {
    api.userInfo({id: form.id}).then((res) => {
        form.username = res.data.username
        form.mobile = res.data.mobile
        form.level = res.data.level
    })
}

const ruleFormRef = ref()
const ok = (formEl) => {
    formEl.validate((valid, fields) => {
        if (valid) {
            api.editUser(form).then((res) => {
                successDeal('修改用户成功！')
                $router.push('/userMangment')
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const cancle = () => {
    $router.go(-1)
}
</script>

<style lang="scss" scoped>
.form-box {
    width: 50%;
}
</style>
